/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { PureComponent, Component, Fragment } from "react";
import { Modal, Button, Table, Radio, Form, Input, Icon, message, Row, Col } from "antd";
import { connect } from "dva";
import StandardSelect from "@/components/Select";
import styles from "./index.less";

const RadioGroup = Radio.Group;
const FormItem = Form.Item;
const InputSearch = Input.Search;

// 调度快递员列表
@Form.create()
@connect(({ allot, loading }) => ({
  getting: loading.effects["allot/getCourier"],
  toing: loading.effects["allot/assignTo"],
  courierData: allot.courierData,
}))
class AllotCourier extends PureComponent {
  constructor(props) {
    super(props);
    const { showType = 0, showRefresh = true } = props;
    this.showType = showType;
    this.showRefresh = showRefresh;
    this.state = {};
    this.columns =
      showType === 0
        ? [
            {
              width: "60%",
              align: "center",
              title: "配送员",
              dataIndex: "courier_name",
              render(val, record) {
                return `${val}(${record.courier_mobile})`;
              },
            },
            {
              width: "40%",
              align: "center",
              title: "进行中数量",
              dataIndex: "num",
            },
          ]
        : [
            {
              width: "10%",
              align: "center",
              dataIndex: "courier_id",
              render(val) {
                return <Radio value={val} />;
              },
            },
            {
              width: "30%",
              align: "center",
              title: "姓名",
              dataIndex: "courier_name",
            },
            {
              width: "30%",
              align: "center",
              title: "手机号",
              dataIndex: "courier_mobile",
            },
            {
              width: "30%",
              align: "center",
              title: "进行中数量",
              dataIndex: "num",
            },
          ];
  }

  componentDidMount() {
    this.getCourier();
  }

  // 获取快递员
  getCourier = data => {
    const { dispatch, form } = this.props;
    const formData = form.getFieldsValue();
    const { key: is_work } = formData.is_work || { key: "1" };
    dispatch({
      type: "allot/getCourier",
      payload: {
        ...formData,
        is_work,
        ...data,
      },
    });
  };

  handleChange = data => {
    this.getCourier({
      is_work: data.key,
    });
  };

  handleSearch = val => {
    this.getCourier({
      courier_name: val,
    });
  };

  // 快递员表格行配置
  handleCourierRow = record => {
    if (this.showType === 0) return;
    return {
      style: {
        cursor: "pointer",
      },
      onClick: () => {
        const { onCourierChange } = this.props;
        if (onCourierChange) {
          onCourierChange(record);
        }
      },
    };
  };

  handleRefresh = () => {
    const { onRefresh } = this.props;
    this.getCourier();
    onRefresh && onRefresh();
  };

  render() {
    const {
      getting,
      courierData,
      form,
      searchProps,
      tableProps,
      currentCourierData,
      courierFilter,
    } = this.props;
    const { result, no_working = 0, working = 0 } = courierData || {};
    const courierTable = {
      dataSource: courierFilter ? courierFilter([...result]) : result,
      pagination: false,
    };
    return (
      <Fragment>
        {this.showRefresh && (
          <FormItem>
            <Button type="primary" onClick={this.handleRefresh}>
              <Icon type="reload" spin={getting} />
              刷新数据
            </Button>
          </FormItem>
        )}
        <div className={`${styles.allotModal} allot-data-wrapper`}>
          <Row gutter={8} className={`allot-search-${this.showType === 0 ? "has" : "unhas"}`}>
            <Col sm={10}>
              {this.showType === 0 &&
                form.getFieldDecorator("is_work", {
                  initialValue: {
                    key: "1",
                    label: "接单中",
                  },
                })(
                  <StandardSelect
                    onChange={this.handleChange}
                    style={{ width: "100%" }}
                    labelInValue
                    placeholder="请选择接单状态"
                    options={[
                      {
                        code: "1",
                        name: `接单中${working || 0}`,
                      },
                      {
                        code: "0",
                        name: `休息中${no_working || 0}`,
                      },
                    ]}
                  />
                )}
            </Col>
            <Col sm={14}>
              {form.getFieldDecorator("courier_name")(
                <InputSearch
                  autoComplete="off"
                  onSearch={this.handleSearch}
                  style={{ width: "100%" }}
                  placeholder="姓名/手机号"
                  {...searchProps}
                />
              )}
            </Col>
          </Row>
          <RadioGroup value={currentCourierData && currentCourierData.courier_id}>
            <Table
              loading={getting}
              onRow={this.handleCourierRow}
              rowKey="courier_id"
              size="small"
              columns={this.columns}
              {...tableProps}
              {...courierTable}
            />
          </RadioGroup>
        </div>
      </Fragment>
    );
  }
}

// 调度弹窗
@connect(({ loading }) => ({
  toing: loading.effects["allot/assignTo"],
}))
class AllotCourierModal extends Component {
  state = {
    visible: false,
  };

  static getDerivedStateFromProps(nextProps) {
    if ("visible" in nextProps) {
      return { visible: nextProps.visible };
    }
    return null;
  }

  handleCancel = () => {
    this.setVisible(false);
  };

  setVisible(visible) {
    const props = this.props;
    if (!("visible" in props)) {
      this.setState({ visible });
    }
    const { onVisibleChange } = props;
    if (onVisibleChange) {
      onVisibleChange(visible);
    }
    if (!visible) {
      this.setState({
        currentCourierData: null,
      });
    }
  }

  handleOk = () => {
    const { currentCourierData } = this.state;
    const { currentAllotData, dispatch, onAssign } = this.props;
    if (!currentCourierData) {
      message.error("请先勾选快递员！");
      return;
    }
    if (!currentAllotData) {
      message.error("请选择订单！");
      return;
    }
    const { orderNumber: order_id, status } = currentAllotData;
    const { courier_id, courier_name, courier_mobile } = currentCourierData;
    dispatch({
      type: "allot/assignTo",
      payload: {
        type: status === "published" ? 1 : 2,
        order_id,
        courier_id,
        courier_name,
        courier_mobile,
      },
    }).then(res => {
      if (res.code == 0) {
        this.setVisible(false);
      }
      if (onAssign) {
        onAssign(res);
      }
    });
  };

  render() {
    const { visible, currentCourierData } = this.state;
    const { currentAllotData, toing } = this.props;
    const statusText =
      currentAllotData && currentAllotData.status === "published" ? "分配" : "改派";
    return (
      <Modal
        okButtonProps={{
          loading: toing,
        }}
        okText={statusText}
        title={`配送员${statusText}`}
        onCancel={this.handleCancel}
        visible={visible}
        centered
        onOk={this.handleOk}
      >
        <AllotCourier
          courierFilter={list => {
            return list && list.filter(item => item.courier_id != currentAllotData.courierId);
          }}
          currentCourierData={currentCourierData}
          onCourierChange={data => {
            this.setState({
              currentCourierData: data,
            });
          }}
          showRefresh={false}
          showType={1}
          tableProps={{
            scroll: { y: 300 },
          }}
          searchProps={{
            enterButton: true,
          }}
        />
      </Modal>
    );
  }
}

export { AllotCourierModal as default, AllotCourier };
